package org.bozo.im.service.protocols.xmpp.session;

import java.util.ArrayList;
import java.util.Hashtable;

import org.bozo.im.service.Constants;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.stanza.task.Task;

import android.util.Log;

public class XMPPTaskProcessor {

	private ArrayList<Task> mTasks;
	private Hashtable<String, ArrayList<Task>> mIdedTasks;
	private XMPPSession mSession;

	public XMPPTaskProcessor(XMPPSession pSession) {
		mTasks = new ArrayList<Task>();
		mIdedTasks = new Hashtable<String, ArrayList<Task>>();
		mSession = pSession;
	}

	public void pushTask(Task pTask) {

		if (!pTask.isUnique() || !mTasks.contains(pTask)) {
			mTasks.add(pTask);
		}
	}

	public void pushTask(Task pTask, String pId) {
		ArrayList<Task> lTasks = mIdedTasks.get(pId);

		if (lTasks == null) {
			lTasks = new ArrayList<Task>();
			mIdedTasks.put(pId, lTasks);
		}

		lTasks.add(pTask);
	}

	public void cancel() {
		mTasks.clear();
	}

	public void processTasks() {

		StringBuilder lBuilder = new StringBuilder();

		while (!mTasks.isEmpty()) {

			Task lTask = mTasks.get(0);
			if (lTask != null) {
				try {
					lTask.doTask(mSession, lBuilder);
				} catch (Exception e) {
					// ---------------------------------------------------------------------------------------
					Log.e(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.session.XMPPTaskProcessor.processTasks ---------- An Exception has been caught", e);
					// ---------------------------------------------------------------------------------------
				}
			}

			synchronized (mTasks) {
				if (!mTasks.isEmpty())
					mTasks.remove(0);
			}
		}

		if (lBuilder.length() != 0)
			mSession.getWriter().write(lBuilder);
	}

	public void processTasks(String pId) {

		ArrayList<Task> lTasks = mIdedTasks.get(pId);

		if (lTasks != null) {

			StringBuilder lBuilder = new StringBuilder();

			for (Task lTask : lTasks) {
				try {
					lTask.doTask(mSession, lBuilder);
				} catch (Exception e) {
					// ---------------------------------------------------------------------------------------
					Log.e(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.session.XMPPTaskProcessor.processTasks ---------- An Exception has been caught", e);
					// ---------------------------------------------------------------------------------------
				}
			}

			mIdedTasks.remove(pId);

			if (lBuilder.length() != 0)
				mSession.getWriter().write(lBuilder);
		}

	}
}